import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sports_new/entity/expert/zq_hot_expert_entity.dart';
import 'package:sports_new/entity/match/expert_views_entity.dart';
import 'package:sports_new/server/api/live_api.dart';
import 'package:sports_new/utils/widget_utils.dart';
import 'package:sports_new/widgets/circular.dart';
import 'package:sports_new/widgets/loading/loading_widget.dart';
import 'package:sports_new/widgets/base/qkd_text.dart';
import '../../../resources/colours.dart';
import '../../../server/api/expert_api.dart';
import '../../../utils/routes.dart';
import '../../../utils/utils.dart';
import 'hot_expert_item.dart';
import '../../../widgets/ladder_tab_bar.dart';

enum HotBoardType { league, live }

class HotBoardController extends ChangeNotifier {
  final HotBoardType type;
  final int sportsId;
  final int? leagueId;
  final String? leagueName;
  HotBoardController(
      {required this.type,
      required this.sportsId,
      this.leagueId,
      this.leagueName});
  HotBoardController.league(
      {required this.sportsId,
      required this.leagueId,
      required this.leagueName})
      : type = HotBoardType.league;
  HotBoardController.live({required this.sportsId})
      : type = HotBoardType.live,
        leagueId = null,
        leagueName = null;

  List<HotExpertEntity>? expertList;

  void getData() async {
    switch (type) {
      case HotBoardType.league:
        expertList = await ExpertApi.getMatchExpertHot(leagueId, sportsId);
        break;
      case HotBoardType.live:
        expertList = await ExpertApi.getRenqiExpertHot(sportsId);
        // LiveApi.getLiveExpertHot(sportsId);
        break;
    }
    notifyListeners();
  }
}

class HotExpertBoard extends StatefulWidget {
  const HotExpertBoard(
      {super.key, required this.controller, this.eventType, this.eventParam});

  final HotBoardController controller;
  final String? eventType;
  final dynamic eventParam;

  @override
  State<HotExpertBoard> createState() => _HotExpertBoardState();
}

class _HotExpertBoardState extends State<HotExpertBoard> {
  HotBoardController get controller => widget.controller;

  int _current = 0;

  set current(int value) => setState(() => _current = value);

  @override
  void initState() {
    controller.getData();
    super.initState();
  }

  @override
  void didChangeDependencies() {
    controller.addListener(() {
      setState(() {});
    });
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    List<List<HotExpertEntity>>? list = controller.expertList?.splitEvery(5);
    return LoadingWidget<bool>(
      isLoading: controller.expertList == null,
      loading: Container(),
      data: controller.expertList?.length == 0,
      noData: Container(),
      child: () => Circular(
          radius: 8,
          color: Colours.white,
          clipBehavior: Clip.antiAlias,
          child: Stack(
            children: [
              Image.asset(
                Utils.getImgPath(
                    'expert_hot_bg${controller.type == HotBoardType.league ? "" : "_blue"}.png'),
                fit: BoxFit.fitWidth,
              ),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      QkdText(
                        controller.type == HotBoardType.league
                            ? "${controller.leagueName ?? ""}专家榜"
                            : "人气专家",
                        fontSize: 15,
                        fontWeight: FontWeight.w600,
                        needCenter: true,
                      ).paddingAll(12),
                      const Spacer(),
                      if (controller.type != HotBoardType.live)
                        GestureDetector(
                            onTap: () => Get.toNamed(Routes.expertTop,
                                arguments: controller.sportsId - 1,
                                parameters: {"pageIndex": "3"}),
                            child: Padding(
                              padding: const EdgeInsets.all(12),
                              child: Row(
                                children: [
                                  const QkdText(
                                    "更多专家",
                                    fontSize: 12,
                                    color: Colours.grey99,
                                    needCenter: true,
                                  ),
                                  Container(width: 2),
                                  Image.asset(
                                    Utils.getImgPath("arrow_right_36.png"),
                                    width: 12,
                                    color: Colours.grey99,
                                  )
                                ],
                              ),
                            ))
                    ],
                  ),
                  CarouselSlider(
                      options: CarouselOptions(
                        clipBehavior: Clip.none,
                        scrollPhysics: const ClampingScrollPhysics(),
                        height: 78,
                        viewportFraction: 1,
                        enableInfiniteScroll:
                            (list?.length ?? 0) > 1 ? true : false,
                        autoPlay: false,
                        onPageChanged: (index, reason) => current = index,
                      ),
                      items: list
                          ?.map<Widget>((e) => Row(
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  ...List.generate(
                                      e.length,
                                      (index) => Expanded(
                                            child: HotExpertItem(
                                              entity: e[index],
                                              sportsId: controller.sportsId,
                                              eventType: widget.eventType,
                                            ),
                                          )),
                                  if (e.length < 5)
                                    ...List.generate(5 - e.length,
                                        (index) => Expanded(child: Container()))
                                ],
                              ))
                          .toList()),
                  if ((list?.length ?? 0) > 1)
                    SizedBox(
                        height: 12,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: List<Widget>.generate(
                              list?.length ?? 0,
                              (index) => AnimatedContainer(
                                  duration: const Duration(milliseconds: 100),
                                  width: _current == index ? 8 : 3,
                                  height: 3,
                                  margin:
                                      const EdgeInsets.symmetric(horizontal: 4),
                                  decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(1.5),
                                      color: _current == index
                                          ? Colours.main
                                          : Colours.greyCC))),
                        ).paddingOnly(right: 16))
                  else
                    Container(height: 12)
                ],
              )
            ],
          )),
    );
  }
}
